/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_products/gitcan.htm
 *
 * gitcan is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.gitcan.action.equipment;

import java.util.List;

import org.zhiqim.gitcan.dbo.GitDatabase;
import org.zhiqim.gitcan.dbo.GitDatabaseEx;
import org.zhiqim.gitcan.dbo.GitIdc;
import org.zhiqim.gitsolo.dao.GitMemberDao;
import org.zhiqim.gitsolo.dao.GitProjectDao;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.StdSwitchAction;
import org.zhiqim.httpd.validate.ones.IsIntegerValue;
import org.zhiqim.httpd.validate.ones.IsLen;
import org.zhiqim.httpd.validate.ones.IsNotEmpty;
import org.zhiqim.httpd.validate.onex.IsInteger;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.ZTable;
import org.zhiqim.orm.ZView;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;

/**
 * 数据库管理，支持数据库的创建、删除和修改权限
 *
 * @version v1.0.0 @author zhichenggang 2014-3-21 新建与整理
 */
public class DatabaseAction extends StdSwitchAction
{
    @Override
    protected void validateId(HttpRequest request)
    {
        request.addValidate(new IsNotEmpty("databaseId", "请选择一个选项"));
    }

    @Override
    protected void validateForm(HttpRequest request)
    {
        request.addValidate(new IsInteger("idcId", "请选择机房"));
        request.addValidate(new IsLen("databaseName", "数据库名称不能为空，[1, 32]范围", 1, 32));
        request.addValidate(new IsNotEmpty("databaseIp", "数据库IP或域名不能为空"));
        request.addValidate(new IsIntegerValue("databaseType", "数据库类型仅支持[mysql/oracle/mssql/postpresql]", 0, 3));
        request.addValidate(new IsNotEmpty("databaseUser", "数据库管理员账号不能为空"));
        request.addValidate(new IsIntegerValue("databasePort", "数据库监听端口不能为空，[1, 65534]范围", 1, 65534));
        request.addValidate(new IsIntegerValue("databaseSeq", "数据库排序必须是[0, 999999]范围的非负整数", 0, 999999));
    }

    @Override
    protected void list(HttpRequest request) throws Exception
    {
        int pageNo = request.getParameterInt("page", 1);
        int pageSize = request.getContextAttributeInt("zmr_page_size", 20);
        
        Selector selector = new Selector();
        selector.addMust("projectId", GitProjectDao.getProjectId(request));
        selector.addMaybeLike("databaseName", request.getParameter("databaseName"));
        selector.addOrderbyAsc("databaseSeq");
        
        PageResult<GitDatabaseEx> result = ORM.get(ZView.class, request).page(GitDatabaseEx.class, pageNo, pageSize, selector);
        result.addConditionMap(request.getParameterMap());
        
        request.setAttribute("result", result);
    }
    
    @Override
    protected void add(HttpRequest request) throws Exception
    {
        Selector selector = new Selector();
        selector.addMust("projectId", GitProjectDao.getProjectId(request));
        selector.addOrderbyAsc("idcSeq");
        
        List<GitIdc> list = ORM.get(ZTable.class, request).list(GitIdc.class, selector);
        request.setAttribute("list", list);
    }

    @Override
    protected void modify(HttpRequest request) throws Exception
    {
        long databaseId = request.getParameterLong("databaseId");
        GitDatabase item = ORM.get(ZTable.class, request).item(GitDatabase.class, databaseId);
        
        if (!GitProjectDao.chkProjectId(request, item.getProjectId()))
        {//判断是否切换了默认项目
            return;
        }
        
        request.setAttribute("item", item);
    }

    @Override
    protected void insert(HttpRequest request) throws Exception
    {
        String databasePassword = request.getParameter("databasePassword");
        if (Validates.isEmptyBlank(databasePassword))
        {
            request.returnHistory("数据库管理员密码不能为空");
            return;
        }
        
        long projectId = GitProjectDao.getProjectId(request);
        String databaseIp = request.getParameter("databaseIp");
        if (ORM.get(ZTable.class, request).count(GitDatabase.class, new Selector("projectId", projectId).addMust("databaseIp", databaseIp)) > 0)
        {
            request.returnHistory("该数据库IP已存在，请不要重复增加");
            return;
        }
        
        long idcId = request.getParameterLong("idcId");
        String databaseName = request.getParameter("databaseName");
        int databaseType = request.getParameterInt("databaseType");
        String databaseUser = request.getParameter("databaseUser");
        int databasePort = request.getParameterInt("databasePort");
        int databaseSeq = request.getParameterInt("databaseSeq");
        String databaseExpirationDate = request.getParameter("databaseExpirationDate");
        
        GitDatabase item = new GitDatabase();
        item.setProjectId(projectId);
        item.setIdcId(idcId);
        item.setDatabaseId(Ids.longId());
        item.setDatabaseName(databaseName);
        item.setDatabaseIp(databaseIp);
        item.setDatabaseType(databaseType);
        item.setDatabaseUser(databaseUser);
        item.setDatabasePassword(databasePassword);
        item.setDatabasePort(databasePort);
        item.setDatabaseSeq(databaseSeq);
        item.setDatabaseExpirationDate(databaseExpirationDate);
        
        ORM.get(ZTable.class, request).insert(item);
        
        GitMemberDao.report(request, projectId, request.getSessionName(), "创建了数据库", databaseName);
    }

    @Override
    protected void update(HttpRequest request) throws Exception
    {
        long databaseId = request.getParameterLong("databaseId");
        GitDatabase item = ORM.get(ZTable.class, request).item(GitDatabase.class, databaseId);
        if(item == null)
        {
            request.returnHistory("数据库不存在，请重新选择");
            return;
        }
        
        if (!GitProjectDao.chkProjectId(request, item.getProjectId()))
        {//判断是否切换了默认项目
            return;
        }
        
        Updater updater = new Updater();
        updater.addMust("databaseId", databaseId);
        updater.addField("databaseName", request.getParameter("databaseName"));
        updater.addField("databaseStatus", request.getParameterInt("databaseStatus"));
        updater.addField("databasePort", request.getParameterInt("databasePort"));
        updater.addField("databaseUser", request.getParameter("databaseUser"));
        updater.addField("databaseSeq", request.getParameterInt("databaseSeq"));
        updater.addField("databaseExpirationDate", request.getParameter("databaseExpirationDate"));
        
        String databasePassword = request.getParameter("databasePassword");
        if (Validates.isNotEmpty(databasePassword))
        {//密码不为空才修改
            updater.addField("databasePassword", databasePassword);
        }
        
        ORM.get(ZTable.class, request).update(GitDatabase.class, updater);
        
        GitMemberDao.report(request, item.getProjectId(), request.getSessionName(), "修改了数据库", request.getParameter("databaseName"));
    }

    @Override
    protected void delete(HttpRequest request) throws Exception
    {
        long databaseId = request.getParameterLong("databaseId");
        GitDatabase item = ORM.get(ZTable.class, request).item(GitDatabase.class, databaseId);
        if(item == null)
        {
            request.returnHistory("数据库不存在，请重新选择");
            return;
        }
        
        if (!GitProjectDao.chkProjectId(request, item.getProjectId()))
        {//判断是否切换了默认项目
            return;
        }
        
        ORM.get(ZTable.class, request).delete(GitDatabase.class, databaseId);
        
        GitMemberDao.report(request, item.getProjectId(), request.getSessionName(), "删除了数据库", item.getDatabaseName());
    }
}
